import pymongo
from urllib import parse
from analysis import util
import datetime

from analysis.FenxiModel import MatchModel
from loaddata import config
from loaddata.ComDatabase import MongoDatabase

'''
mongodb数据相关操作
'''

# 处理竞猜网数据
class JinCaiDatabase(MongoDatabase):
    def __init__(self):
        MongoDatabase.__init__(self)

    # 查询配置
    def get_jincai_config(self, filter):
        # 向集合插入一条数据
        collection = self.db.jincai_config
        result = collection.find_one(filter)  # 查询条件，指定要更新的文档
        if result:
            return result
        else:
            filter["setValue"] = {}
            collection.insert_one(filter)
            return collection.find_one(filter)  # 查询条件，指定要更新的文档

    # 批量保存
    def batch_sava_to_jincai(self, ds):
        # 保持前先查看一下这些数据是否已经开奖并已经保持，这里这是最未开奖并且没有存在的记录进行保存更新
        filter = {"key": "updata_flag"}
        flag = self.get_jincai_config(filter)
        # 如果存在，就更新,否则就添加
        addds = []
        for d in ds:
            updata_flag = flag["setValue"]
            # 1表示已经开奖
            if updata_flag.get(d["matchNo"]):
                continue
            else:
                flag["setValue"][d["matchNo"]] = 1
                addds.append(d)
        if len(addds) > 0:
            # 向集合插入一条数据
            collection = self.db.jincai
            # 执行批量插入操作
            collection.insert_many(addds)
            # 更新标记
            self.set_to_jincai_config(filter, flag)
            # 同步开奖格式化信息
            self.batch_sava_to_jincai_kaijiang(addds)

    # 设置配置
    def set_to_jincai_config(self, filter, data):
        # 向集合插入一条数据
        collection = self.db.jincai_config
        new_values = {'$set': data}  # 更新内容，使用$set运算符来更新特定字段的值
        result = collection.update_one(filter, new_values)  # 调用update_one()函数进行更新
        print("Updated documents count: ", result.modified_count)  # 输出被更新的文档数量

    # 查询
    def get_jincai(self, filter):
        collection = self.db.jincai
        ds = collection.find(filter).sort({"matchTime": -1})  # 查询条件
        historys = []
        for d in ds:
            sectionsNo999 = d.get("sectionsNo999")
            if sectionsNo999 == '取消' or sectionsNo999 == '无效场次' or sectionsNo999 == '':
                continue
            historys.append(d)
        return historys

    # 查询
    def get_selling(self, filter):
        collection = self.db.selling
        result = collection.find(filter)  # 查询条件
        return result

    # 根据matchId查询毕设场次
    def get_selling_by(self,matchId):
        collection = self.db.selling
        result = collection.find({})  # 查询条件
        res = None
        if result:
            matchInfoList = result[0].get("value").get("matchInfoList")
            for infos in matchInfoList:
                subMatchList = infos.get("subMatchList")
                for s in subMatchList:
                    if int(matchId) == s.get("matchId"):
                        res = s
                        break
        return res

    # 获取要分析的数据
    def getSellingData(self,matchId):
        return self.get_selling_by(matchId)

    # 根据matchId查询历史比赛场次
    def getHistoryDataByMatchID(self,matchId):
        return self.get_jincai({"matchId": int(matchId)})[0]

    # 获取近N年的历史数据
    def getHistoryDataByNearYear(self,n):
        days = 365*n
        # 获取当前时间
        end_of_year = datetime.datetime.now()
        start_of_year = end_of_year - datetime.timedelta(days=days)
        datestart = datetime.datetime.strftime(start_of_year, '%Y-%m-%d')
        dateend = datetime.datetime.strftime(end_of_year, '%Y-%m-%d')
        query = {'matchTime': {'$gte': datestart, '$lt': dateend}}
        ds = self.get_jincai(query)
        return ds

    # 获取近N个月的历史数据(总进球)
    def getHistoryDataByNearMonth(self,n):
        days = 30*n
        # 获取当前时间
        end_of_year = datetime.datetime.now()
        start_of_year = end_of_year - datetime.timedelta(days=days)
        datestart = datetime.datetime.strftime(start_of_year, '%Y-%m-%d')
        dateend = datetime.datetime.strftime(end_of_year, '%Y-%m-%d')
        query = {'matchTime': {'$gte': datestart, '$lt': dateend}}
        ds = self.get_jincai(query)
        return ds

    # 获取历史数据(开始年到现在)
    def getHistoryDataFromYear(self,year):
        end_of_year = datetime.datetime.now()
        start_of_year = datetime.datetime(year=year, month=1, day=1)
        datestart = datetime.datetime.strftime(start_of_year, '%Y-%m-%d')
        dateend = datetime.datetime.strftime(end_of_year, '%Y-%m-%d')
        query = {'matchTime': {'$gte': datestart, '$lt': dateend}}
        ds = self.get_jincai(query)
        return ds

    # 获取历史数据(指定某一年的数据)
    def getHistoryDataByYear(self,year):
        # 想要查询的年份
        start_of_year = datetime.datetime(year=year, month=1, day=1)
        end_of_year = start_of_year + datetime.timedelta(days=365) - datetime.timedelta(microseconds=1)
        datestart = datetime.datetime.strftime(start_of_year, '%Y-%m-%d')
        dateend = datetime.datetime.strftime(end_of_year, '%Y-%m-%d')
        query = {'matchTime': {'$gte': datestart, '$lt': dateend}}
        ds = self.get_jincai(query)
        return ds

    # 获取历史数据
    def getHistoryModel(self):
        ds = self.get_jincai({})
        res = []
        for d in ds:
            res.append(MatchModel(d))
        return res

    # 获取历史数据
    def getSellingModel(self):
        result = self.get_selling({})
        matchInfoList = result[0].get("value").get("matchInfoList")
        res ={}
        for days in matchInfoList:
            ms = []
            subMatchList = days.get("subMatchList")
            for m in subMatchList:
                ms.append(MatchModel(m))
            res[days.get("businessDate")] = ms
        return res

    # 获取历史数据(开始时间，结束时间)
    def getHistoryDataBystart(self,datestart,dateend):
        query = {'matchTime': {'$gte': datestart, '$lt': dateend}}
        ds = self.get_jincai(query)
        return ds



    # 保存或跟新售卖比赛信息
    def savaOrUpdataSelling(self, d):
        collection = self.db.selling
        # 清空集合
        collection.delete_many({})
        # 再插入
        collection.insert_one(d)
        # 顺便更新到未开始的比赛表中
        self.savaOrUpdataMatchs()


    # 获取未开始的比赛信息
    def findMatchs(self,query):
        collection = self.db.jincai_matchs
        ds = collection.find(query)
        return ds

    # 保存更新未开始的比赛数据
    def savaOrUpdataMatchs(self):
        matchs_collection = self.db.jincai_matchs
        selling_collection = self.db.selling
        sels = selling_collection.find({})
        # 获取所有的日期比赛
        matchInfoList = sels[0].get("value").get("matchInfoList")
        # 每天的比赛
        for n in matchInfoList:
            # 每场比赛信息
            for m in n.get("subMatchList"):
                if m.get("sellStatus")!='1':
                    continue
                # 基本信息
                info = {
                    'matchId': m.get("matchId"),
                    'awayTeamAbbName': m.get("awayTeamAbbName"),
                    'awayTeamId': m.get("awayTeamId"),
                    'homeTeamAbbName': m.get("homeTeamAbbName"),
                    'homeTeamId': m.get("homeTeamId"),
                    'leagueAbbName': m.get("leagueAbbName"),
                    'leagueId': m.get("leagueId"),
                    'businessDate': m.get("businessDate"),
                    'matchDate': m.get("matchDate"),
                    'matchNum': m.get("matchNum"),
                    'matchNumDate': m.get("matchNumDate"),
                    'matchNumStr': m.get("matchNumStr"),
                    'matchTime': m.get("matchTime"),
                    'sellStatus': m.get("sellStatus"),
                    'iskai': 0  # 是否比赛结束，0：未结束，1：已结束
                }
                oddsHistory = m.get("fixedBonus").get("oddsHistory")
                #   比赛临场指数
                exponent = {
                    'crsList':oddsHistory.get("crsList"),
                    'hhadList': oddsHistory.get("hhadList"),
                    'ttgList': oddsHistory.get("ttgList"),
                    'hadList': oddsHistory.get("hadList"),
                    'hafuList': oddsHistory.get("hafuList")
                }
                # 让球
                goalLine = oddsHistory.get("hhadList")[0].get("goalLine")
                info["goalLine"] = goalLine
                query = {'info.matchId': m.get("matchId")}
                data = {'info': info,"exponent":exponent}
                updata = {'$set': {"exponent":exponent}}
                doc = matchs_collection.find_one(query)
                if doc:
                    matchs_collection.update_one(query, updata)  # 更新结果比分
                else:
                    matchs_collection.insert_one(data)

    # 保存或跟未开奖的比赛及分析数据
    def savaOrUpdataMatchScore(self, d):
        collection = self.db.jincai_matchs
        query = {'info.matchId': d.get("matchId")}
        updata = {'$set': {"sectionsNos": d.get("sectionsNos"),"info": {"iskai":1}}}
        collection.update_one(query,updata)  # 更新结果比分

    # 保存或更新格式化后的开奖信息
    def savaKJ(self, d):
        collection = self.db.jincai_kaijiang
        query = {"base_info":{"matchId":d.get("base_info").get("matchId")}}
        # 判断是否已经存在
        result = collection.find_one(query)  # 查询条件，指定要更新的文档
        if result:
            pass
        else:
            # 再插入
            collection.insert_one(d)

    # 查询开奖
    def get_jincai_kaijiang(self, filter):
        collection = self.db.jincai_kaijiang
        result = collection.find(filter)  # 查询条件
        return result

    # 查询开奖
    def get_one_jincai_kaijiang(self, filter):
        collection = self.db.jincai_kaijiang
        result = collection.find_one(filter)  # 查询条件
        return result


    # 批量保存开奖信息
    def batch_sava_to_jincai_kaijiang(self, ds):
        tokjs = util.formatKJData(ds)
        mids = [m.get("base_info").get("matchId") for m in tokjs]
        kjs = self.get_jincai_kaijiang({"base_info.matchId":mids})
        rs = []
        for a in tokjs:
            af = True
            for k in kjs:
                if a.get("base_info").get("matchId") == k.get("base_info").get("matchId"):
                    af = False
                    break
            if af:
                rs.append(a)
        collection = self.db.jincai_kaijiang
        # 执行批量插入操作
        collection.insert_many(rs)


    # 获取历史数据(开始年到现在)
    def getKJHistoryDataFromYear(self,year):
        end_of_year = datetime.datetime.now()
        start_of_year = datetime.datetime(year=year, month=1, day=1)
        datestart = datetime.datetime.strftime(start_of_year, '%Y-%m-%d')
        dateend = datetime.datetime.strftime(end_of_year, '%Y-%m-%d')
        query = {'base_info.matchTime': {'$gte': datestart, '$lt': dateend}}
        ds = self.get_jincai_kaijiang(query)
        return ds


# 处理500wan网数据
class Wan500Database:
    def __init__(self):
        MongoDatabase.__init__(self)

    # 保存或更新格式化后的比赛信息
    def batch_sava_to_matchInfo(self, ds):
        # 500wan的比赛信息表
        collection = self.db.wan500_matchs
        # 先清空存在的这一批数据
        collection.delete_many({"fid":{"$in":[d.get("fid") for d in ds]}})
        # 执行批量插入操作
        if ds:
            collection.insert_many(ds)

    # 保存或更新格式化后的欧赔信息
    def batch_sava_to_ouzhi(self, ds):
        # 500wan的比赛信息表
        collection = self.db.wan500_ouzhi
        # 先清空存在的这一批数据
        collection.delete_many({"fid":{"$in":[d.get("fid") for d in ds]}})
        # 执行批量插入操作
        if ds:
            collection.insert_many(ds)


# 处理排列三数据
class PailieDatabase:
    def __init__(self):
        MongoDatabase.__init__(self)

    # 保存或更新格式化后的比赛信息
    def batch_sava_to_pailie(self, ds):
        collection = self.db.pailie
        rs = collection.find({"lotteryDrawNum":{"$in":[d.get("lotteryDrawNum") for d in ds]}})
        ss = []
        if rs:
            for d in ds:
                f = True
                for r in rs:
                    if d.get("lotteryDrawNum") == r.get("lotteryDrawNum"):
                        f = False
                        break
                if f:
                    ss.append(d)

        # 执行批量插入操作
        if ss:
            # 先做一个反向排序，因为最开始的是最近的，我们要先保存以前的数据
            ss.sort(key=lambda d: d.get("lotteryDrawNum"),reverse=False)
            collection.insert_many(ss)
        return ss

    # 判断是否存在
    def isexit(self,ds):
        collection = self.db.pailie
        rs = collection.find({"lotteryDrawNum":{"$in":[d.get("lotteryDrawNum") for d in ds]}})
        return [d.get("lotteryDrawNum") for d in rs]